import React, { PureComponent, Fragment } from 'react';

import { connect } from 'umi';
import moment from 'moment';
import { Row, Col, Card, Table, Form, Modal, Popover, Divider, message } from 'antd';
import { get as _get } from 'object-path';
// import uniqueId from 'lodash/uniqueId';
// import cookie from 'js-cookie';
import { Pagination } from '@/components';
import { formatMessage } from 'umi';
import { history } from 'umi';
import DataPick2 from '@/components/DatePicker2';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { dateConversion, dateConversion2 } from '@/utils/utils';
import { withRoutePage } from '@/utils/enhanceUtils';
import request from '@/utils/request';
import styles from './Holiday.less';

@withRoutePage
@connect(({ holiday, loading }) => ({
    holiday,
    loading
}))
@Form.create()
class Holiday extends PureComponent {
    state = {
        visible: false,
        dateOption: [
            {
                en: 'year',
                cn: '今年'
            },
            {
                en: 'month',
                cn: '本月'
            },
            {
                en: 'week',
                cn: '本周'
            }
        ],
        columns: [],
        times: [
            moment(
                moment()
                    .month(moment().month())
                    .startOf('month')
                    .format('YYYY-MM-DD')
            ),
            moment()
        ],
        filters: [],
        filtersLeaveStatus: [],
        columnsModal: [
            {
                title: formatMessage({
                    id: 'form.thead.userNo'
                }),
                dataIndex: 'userNo',
                key: 'userNo'
            },
            {
                title: formatMessage({
                    id: 'form.thead.attDatetime'
                }),
                dataIndex: 'attDatetime',
                key: 'attDatetime'
            },
            {
                title: formatMessage({
                    id: 'form.thead.deviceName'
                }),
                dataIndex: 'deviceName',
                key: 'deviceName'
            }
        ],
        signDate: '',
        filter: {}
    };

    componentDidMount() {
        const { times } = this.state;
        // 判断路由上是否有数据,有数据的话,获取当月日期,重新构建moment进行请求
        if (this.getQuery()) {
            const date = [
                moment(
                    moment(this.getQuery())
                        .startOf('month')
                        .format('YYYY-MM-DD')
                ),
                moment(
                    moment(this.getQuery())
                        .endOf('month')
                        .format('YYYY-MM-DD')
                )
            ];
            this.handleSearch(date, '');
        } else {
            this.handleSearch(times, '');
        }

        this.getTypeListAll();
    }

    componentWillUnmount() {
        const {
            dispatch,
            holiday: { pagination: curPagination }
        } = this.props;

        dispatch({
            type: 'holiday/setPagination',
            pagination: {
                ...curPagination,
                pageSize: 10,
                current: 1
            }
        });
    }

    showModal = () => {
        this.setState({
            visible: true
        });
    };

    setVisible = type => {
        this.setState({
            visible: type
        });
    };

    // 撤销请假
    featchCancellationOfLeave = async record => {
        const { applicationNo } = record;
        const user = JSON.parse(localStorage.getItem('user'));
        const classificationRes = await request(
            `/api/workflowweb/processinstance/v1/getByAdvancedSettingType?classification=LeaveCancelApply&companyId=${user?.companyId}`
        );
        if (classificationRes?.code === 10000) {
            history.push(
                `/personal/portal/apply?id=${classificationRes?.data?.actProcessDefinitionId}&name=${classificationRes?.data?.processName}&applicationNo=${applicationNo}`
            );
        } else {
            message.error(classificationRes.msg);
        }
    };

    // dot圆点渲染
    renderDot = num => {
        let color = '';
        if (num === '1' || num === '4') {
            color = '#52C41A';
        } else if (num === '2') {
            color = '#FFA22D';
        } else if (num === '3') {
            color = '#FF4D4F';
        }
        return <i className={styles.dot} style={{ background: color }}></i>;
    };

    // 撤销申请按钮操作规则
    // 字段vocationEffectives时间段并且是否是三个月之内的
    // 再判断是否是请假已通过
    renderAction = record => {
        const { applicationCancelNo } = record;
        const isOldFlow = !applicationCancelNo.includes('-');
        const url = isOldFlow
            ? '/personal/portal/flow/mine/myApplication/detail'
            : '/personal/portal/myApplication/detail';
        const params = isOldFlow ? { applicationNo: applicationCancelNo } : { applicationNo: applicationCancelNo };

        if (record.showLeaveCancelButton === '') {
            return '';
        }
        if (record.showLeaveCancelButton === 'details') {
            return (
                <Fragment>
                    <a
                        onClick={() => {
                            history.push({
                                pathname: url,
                                query: params
                            });
                        }}
                    >
                        销假详情
                    </a>
                    <Divider type="vertical" />
                </Fragment>
            );
        }
        if (record.showLeaveCancelButton === 'leaveCancelApply') {
            return (
                <Fragment>
                    <a
                        onClick={() => {
                            this.featchCancellationOfLeave(record);
                        }}
                    >
                        撤销请假
                    </a>
                    <Divider type="vertical" />
                </Fragment>
            );
        }
        return '';
    };

    setfilters = () => {
        const {
            holiday: { typelistall, leaveStatus }
        } = this.props;
        const column = [
            {
                title: formatMessage({
                    id: 'form.thead.leaveName'
                }),
                dataIndex: 'leaveName',
                key: 'leaveName',
                filters: []
            },
            {
                title: formatMessage({
                    id: 'form.date.placeholder.start'
                }),
                dataIndex: 'startTime',
                key: 'startTime'
            },
            {
                title: formatMessage({
                    id: 'form.date.placeholder.end'
                }),
                dataIndex: 'endTime',
                key: 'endTime'
            },
            {
                title: formatMessage({
                    id: 'form.thead.leaveLong'
                }),
                dataIndex: 'leaveLong',
                key: 'leaveLong',
                render: text => dateConversion2(text, 8)
            },
            {
                title: '请假状态',
                dataIndex: 'leaveStatus',
                key: 'leaveStatus',
                filters: [],
                render: (text, record) =>
                    leaveStatus &&
                    leaveStatus.map(item => {
                        if (record.leaveStatus && item.dictValue === record.leaveStatus.toString()) {
                            return (
                                <div>
                                    {this.renderDot(record.leaveStatus.toString())}
                                    {item.dictName}
                                </div>
                            );
                        }
                        return '';
                    })
            },
            {
                title: '操作',
                dataIndex: 'action',
                key: 'action',
                render: (text, record) => {
                    const { applicationNo } = record;
                    const isOldFlow = !applicationNo.includes('-');
                    const url = isOldFlow
                        ? '/personal/portal/flow/mine/myApplication/detail'
                        : '/personal/portal/myApplication/detail';
                    const params = { applicationNo };
                    return (
                        // console.log(record, 'record')
                        <Fragment>
                            {this.renderAction(record)}
                            <a
                                onClick={e => {
                                    e.preventDefault();
                                    history.push({
                                        pathname: url,
                                        query: params
                                    });
                                }}
                            >
                                请假详情
                            </a>
                            <Divider type="vertical" />
                            <a onClick={() => this.seeDetail(record)}>打卡记录</a>
                        </Fragment>
                    );
                }
            }
        ];
        // 写入请假类型的筛选
        const arr = [];
        for (let index = 0; index < typelistall.length; index += 1) {
            const list = {
                text: typelistall[index].leaveName,
                value: typelistall[index].leaveName
            };
            arr.push(list);
        }
        column[0].filters = arr;
        // 写入\请假状态
        const arr2 = [];
        for (let index = 0; index < leaveStatus.length; index += 1) {
            const list = {
                text: leaveStatus[index].dictName,
                value: leaveStatus[index].dictValue
            };
            arr2.push(list);
        }
        column[4].filters = arr2;
        this.setState({
            columns: column
        });
    };

    seeDetail = record => {
        const { dispatch } = this.props;
        const parame = {
            employeeCode: record.employeeCode,
            startTime: moment(record.startTime).format('YYYY-MM-DD'),
            endTime: moment(record.endTime).format('YYYY-MM-DD')
        };
        dispatch({
            type: 'holiday/getmyattendancedetail',
            payload: {
                parame
            }
        }).then(() => {
            this.setState({
                signDate: moment(record.startTime).format('YYYY-MM-DD')
            });
            this.showModal();
        });
    };

    getData = type => {
        const { times, filters, filtersLeaveStatus } = this.state;
        const {
            dispatch,
            holiday: { pagination }
        } = this.props;
        const leaverecordParame = {
            startTime: times[0].format('YYYY-MM-DD'),
            endTime: times[1].format('YYYY-MM-DD'),
            leaveCode: _get(filters, []),
            pageNo: type ? 1 : pagination.current,
            pageSize: pagination.pageSize,
            leaveStatus: _get(filtersLeaveStatus, [])
        };
        dispatch({
            type: 'holiday/fetchMyleaverecord',
            payload: {
                leaverecordParame
            }
        });
    };

    getTypeListAll = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'holiday/fetchTypelistall',
            callback: () => {
                dispatch({
                    type: 'holiday/fetchDictionaryList',
                    payload: {
                        code: 'leaveStatus'
                    },
                    callback: () => {
                        this.setfilters();
                    }
                });
            }
        });
    };

    handleSearch = (v, type) => {
        this.setState(
            {
                times: v
            },
            () => {
                this.getData(_get(type, ''));
            }
        );
    };

    // 页码改变
    changeTable = async (pagination, filters) => {
        const {
            dispatch,
            holiday: { pagination: curPagination }
        } = this.props;
        const { filter } = this.state;
        await dispatch({
            type: 'holiday/setPagination',
            pagination: {
                ...curPagination,
                ...pagination
            }
        });
        if (filters && JSON.stringify(filter) !== JSON.stringify(filters)) {
            this.setState({
                filter: filters
            });

            await dispatch({
                type: 'holiday/setPagination',
                pagination: {
                    ...curPagination,
                    current: 1
                }
            });
        }
        this.setState(
            {
                filters: filters && filters.leaveName,
                filtersLeaveStatus: filters && filters.leaveStatus
            },
            () => {
                this.getData();
            }
        );
    };

    // 获取年假点击信息
    getYearMsg = () => {
        const user = JSON.parse(localStorage.getItem('user'));
        const { dispatch } = this.props;
        dispatch({
            type: 'holiday/getPopoverList',
            payload: {
                companyCode: user.companyId,
                // departmentId: user.departmentId,
                employeeCode: user.employeeCode,
                leaveCode: 'CommonYear'
            }
        });
    };

    getPopoverContent = popoverList =>
        popoverList.map(item => (
            <div key={item.leaveCode}>
                {moment(item.startTime).format('YYYYMMDD')}-{moment(item.endTime).format('YYYYMMDD')}：
                {dateConversion(item.value, 8)}
            </div>
        ));

    // 获取路由上的参数
    getQuery = () => {
        let defaultDate;
        if (_get(this.props, 'location.query.date') && _get(this.props, 'location.query.date') !== 'undefined') {
            defaultDate = _get(this.props, 'location.query.date');
        }
        return defaultDate;
    };

    render() {
        const { loading } = this.props;
        const { columns, dateOption, signDate, visible, columnsModal } = this.state;
        const {
            holiday,
            holiday: { pagination, attendancedetail, popoverList = [] }
        } = this.props;

        const myleaverecord = _get(holiday, 'myleaverecord', []);
        const myvocation = _get(holiday, 'myvocation', '');
        return (
            <PageHeaderWrapper>
                <Card
                    title={formatMessage({
                        id: 'stat.name.wdjq'
                    })}
                    className={styles.card}
                    bordered={false}
                >
                    <Row className={styles.datainfo}>
                        <Col sm={24} md={8}>
                            <p>
                                <span>
                                    {formatMessage({
                                        id: 'stat.name.njye'
                                    })}
                                    ：
                                </span>
                                <Popover
                                    content={this.getPopoverContent(popoverList)}
                                    title="年假-可用余额"
                                    onVisibleChange={() => {
                                        this.getYearMsg();
                                    }}
                                    trigger="click"
                                >
                                    <i>
                                        {myvocation.annualBalanceDay}
                                        {formatMessage({
                                            id: 'stat.day'
                                        })}
                                        （{myvocation.annualBalance}
                                        {formatMessage({
                                            id: 'stat.hour'
                                        })}
                                        ）
                                    </i>
                                </Popover>
                            </p>
                            <p>
                                <span>
                                    {formatMessage({
                                        id: 'stat.name.njze'
                                    })}
                                    ：
                                </span>
                                {myvocation.annualSumDay}
                                {formatMessage({
                                    id: 'stat.day'
                                })}
                                （{myvocation.annualSum}
                                {formatMessage({
                                    id: 'stat.hour'
                                })}
                                ）
                            </p>
                            <p>
                                <span>
                                    {formatMessage({
                                        id: 'stat.name.yynj'
                                    })}
                                    ：
                                </span>
                                {myvocation.annualUsedDay}
                                {formatMessage({
                                    id: 'stat.day'
                                })}
                                （{myvocation.annualUsed}
                                {formatMessage({
                                    id: 'stat.hour'
                                })}
                                ）
                            </p>
                        </Col>
                        <Col sm={24} md={8}>
                            <p>
                                <span>
                                    {formatMessage({
                                        id: 'stat.name.jbye'
                                    })}
                                    ：
                                </span>
                                {dateConversion2(myvocation.overtimeBalance)}
                            </p>
                            <p>
                                <span>
                                    {formatMessage({
                                        id: 'stat.name.ljjb'
                                    })}
                                    ：
                                </span>
                                {dateConversion2(myvocation.overtimeSum)}
                            </p>
                            <p>
                                <span>
                                    {formatMessage({
                                        id: 'stat.name.yytx'
                                    })}
                                    ：
                                </span>
                                {dateConversion2(myvocation.overtimeUsed)}
                            </p>
                        </Col>
                    </Row>
                </Card>
                <Card
                    title={formatMessage({
                        id: 'stat.name.qjjl'
                    })}
                    className={styles.card}
                    bordered={false}
                    extra={
                        <DataPick2
                            onSearch={v => {
                                this.handleSearch(v, true);
                            }}
                            dateOption={dateOption}
                            mode="month"
                            defaultDate={_get(this.getQuery())}
                        />
                    }
                >
                    <Table
                        bordered={false}
                        dataSource={myleaverecord}
                        columns={columns}
                        loading={loading.effects['holiday/fetchMyleaverecord']}
                        rowKey="id"
                        onChange={this.changeTable}
                        pagination={false}
                    />
                    <Pagination
                        {...pagination}
                        onChange={this.changeTable}
                        loading={loading.effects['holiday/fetchMyleaverecord']}
                    />
                </Card>
                <Modal
                    title={
                        <div>
                            <div style={{ fontSize: '20px', color: '#333' }}>
                                {formatMessage({
                                    id: 'stat.ckdkjl'
                                })}
                            </div>
                            <p
                                style={{
                                    color: 'rgba(0, 0, 0, .45)',
                                    fontSize: '14px',
                                    marginBottom: 0
                                }}
                            >
                                {signDate}
                                {formatMessage({
                                    id: 'stat.dksj'
                                })}
                            </p>
                        </div>
                    }
                    width={600}
                    footer={null}
                    visible={visible}
                    onOk={() => this.setVisible(false)}
                    onCancel={() => this.setVisible(false)}
                    centered
                >
                    <Table
                        dataSource={attendancedetail}
                        columns={columnsModal}
                        pagination={false}
                        loading={loading.effects['holiday/getmyattendancedetail']}
                        rowKey="id"
                    />
                </Modal>
            </PageHeaderWrapper>
        );
    }
}

export default Holiday;
